﻿using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using XingZhe.Common;

namespace XingZhe.Helpers
{
        public static partial class XingZheHelper
        {
                private static Dictionary<string, string> msgStack = new Dictionary<string, string>();
                static XingZheHelper()
                {
                        XingZheHelper.DeviceUniqueId = XingZheHelper.GetDeviceUniqueId();
                }

                public static string DeviceUniqueId
                {
                        get;
                        private set;
                }

                public static void SetBusyMessage(MessageTypeEnum msgType, string msg, int? milliseconds = null)
                {
                        string strMsgType = msgType.ToString();
                        int length = XingZheHelper.msgStack.Count;

                        if (XingZheHelper.msgStack.ContainsKey(strMsgType))
                        {
                                XingZheHelper.msgStack.Remove(strMsgType);
                        }

                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                                XingZheHelper.msgStack.Add(strMsgType, msg);
                        }

                        if (XingZheHelper.msgStack.Count > 0)
                        {
                                string[] keys = XingZheHelper.msgStack.Keys.ToArray();
                                msg = XingZheHelper.msgStack[keys[XingZheHelper.msgStack.Count - 1]];
                        }

                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                                if (SystemTray.ProgressIndicator != null)
                                {
                                        SystemTray.ProgressIndicator.Text = msg;
                                        SystemTray.ProgressIndicator.IsVisible = !string.IsNullOrWhiteSpace(msg);
                                }
                        });

                        if (!string.IsNullOrWhiteSpace(msg) && milliseconds != null)
                        {
                                DispatcherTimer timer = new DispatcherTimer();
                                timer.Interval = new TimeSpan(0, 0, 0, 0, milliseconds.Value);
                                timer.Tick += (a, b) =>
                                {
                                        XingZheHelper.SetBusyMessage(msgType, string.Empty);
                                        timer.Stop();
                                };

                                timer.Start();
                        }
                }

                public static void LocationConsentMessageBox(Action<bool> onComplete = null)
                {
                        if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
                        {
                                if (onComplete != null)
                                {
                                        onComplete(true);
                                }
                        }
                        else
                        {
                                CustomMessageBox messgeBox = new CustomMessageBox()
                                {
                                        Caption = "行者",
                                        Message = "行者软件必须使用位置服务，才能正常使用。请确认是否允许访问位置服务。",
                                        LeftButtonContent = "允许",
                                        RightButtonContent = "不允许",
                                        IsFullScreen = true
                                };

                                messgeBox.Dismissed += (s1, e1) =>
                                {
                                        switch (e1.Result)
                                        {
                                                case CustomMessageBoxResult.LeftButton:
                                                        IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
                                                        break;
                                                case CustomMessageBoxResult.RightButton:
                                                        IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
                                                        break;
                                                case CustomMessageBoxResult.None:
                                                        break;
                                                default:
                                                        break;
                                        }

                                        IsolatedStorageSettings.ApplicationSettings.Save();


                                        if (onComplete != null)
                                        {
                                                onComplete(e1.Result == CustomMessageBoxResult.LeftButton);
                                        }
                                };

                                messgeBox.Show();
                        }
                }

                private static string GetDeviceUniqueId()
                {
                        object deviceUniqueIdData;
                        DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out deviceUniqueIdData);
                        byte[] bytes = (byte[])deviceUniqueIdData;

                        return Convert.ToBase64String(bytes).Replace("=", "").Replace("+", "").Replace("/", "").ToUpper();
                }

                public static byte[] GZip(byte[] src)
                {
                        MemoryStream basestream = new MemoryStream();
                        GZipOutputStream stream = new GZipOutputStream(basestream);
                        stream.Write(src, 0, src.Length);
                        stream.Flush();
                        stream.Close();

                        return basestream.ToArray();
                }
                public static byte[] UnGZip(byte[] gZip)
                {
                        try
                        {
                                MemoryStream srcStream = new MemoryStream(gZip);
                                GZipInputStream gzipStream = new GZipInputStream(srcStream);

                                MemoryStream outStream = new MemoryStream();

                                byte[] writeData = new byte[4096];

                                while (true)
                                {
                                        int size = gzipStream.Read(writeData, 0, writeData.Length);
                                        if (size > 0)
                                        {
                                                outStream.Write(writeData, 0, size);
                                        }
                                        else
                                        {
                                                break;
                                        }
                                }

                                gzipStream.Close();
                                byte[] outArr = outStream.ToArray();
                                outStream.Close();

                                return outArr;
                                // return System.Text.Encoding.UTF8.GetString(outArr, 0, outArr.Length);
                        }
                        catch
                        {
                                return null;
                        }
                }

        }
}
